package com.atguigu.serviceedu.service.impl;

import com.atguigu.dto.CourseDto;
import com.atguigu.serviceedu.entity.*;
import com.atguigu.serviceedu.entity.form.CourseInfoForm;
import com.atguigu.serviceedu.entity.vo.*;
import com.atguigu.serviceedu.feign.ServiceOssFeignClient;
import com.atguigu.serviceedu.mapper.*;
import com.atguigu.serviceedu.service.EduCourseService;
import com.atguigu.vo.ResultVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-07-26
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    @Autowired
    private EduCourseMapper eduCourseMapper;
    @Autowired
    private EduCourseDescriptionMapper eduCourseDescriptionMapper;
    @Autowired
    private ServiceOssFeignClient serviceOssFeignClient;
    @Autowired
    private EduVideoMapper eduVideoMapper;
    @Autowired
    private EduChapterMapper eduChapterMapper;
    @Autowired
    private EduCourseCollectMapper eduCourseCollectMapper;
    @Autowired
    private EduCommentMapper eduCommentMapper;

    @Override
    public String insertCourseInfo(CourseInfoForm courseInfoForm) {
        //你可以看出courseInfoForm是对前端信息在后端的一个载体，它就像一个船一样，装载了很多货物
        //这些货物，不只是一个表的，它可以分属于不同的表，只不过你在处理的时候将其分开就行了
        EduCourse eduCourse = new EduCourse();//这个对象要插入educourse表
        BeanUtils.copyProperties(courseInfoForm, eduCourse);//把两对象里的共有属性从左边对象赋值到右边对象
        eduCourse.setStatus(EduCourse.COURSE_DRAFT);
        eduCourseMapper.insert(eduCourse);//这个插入后会自动回写id到内存层面的educourse对象中
        String courseId = eduCourse.getId();//所以这里可以get到

        EduCourseDescription eduCourseDescription = new EduCourseDescription();//这个对象要插入educoursedescription
        eduCourseDescription.setId(courseId);
        eduCourseDescription.setDescription(courseInfoForm.getDescription());
        eduCourseDescriptionMapper.insert(eduCourseDescription);
        return courseId;
    }

    @Override
    public CourseInfoForm selectCourseById(String id) {
        EduCourse eduCourse = eduCourseMapper.selectById(id);
        //当然有可能前端传过来的courseid对应的course已经被删了，比如有两个管理员。所以才有下面的if
        if (eduCourse == null) {
            return null;
        }
        //没走if证明该课程是存在的
        EduCourseDescription eduCourseDescription = eduCourseDescriptionMapper.selectById(id);
        //下面就是组装返回对象courseInfoForm
        CourseInfoForm courseInfoForm = new CourseInfoForm();
        BeanUtils.copyProperties(eduCourse, courseInfoForm);
        courseInfoForm.setDescription(eduCourseDescription.getDescription());
        return courseInfoForm;
    }

    @Override
    public boolean updateCourseInfo(CourseInfoForm courseInfoForm) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoForm, eduCourse);
        eduCourseMapper.updateById(eduCourse);

        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoForm.getDescription());
        eduCourseDescription.setId(courseInfoForm.getId());
        eduCourseDescriptionMapper.updateById(eduCourseDescription);
        return true;
    }

    @Override
    public IPage<CourseVO> getConditionCourse(Long currentpage, Long pagesize, CourseQueryVO courseQueryVO) {
        Page<CourseVO> pageParm = new Page<>(currentpage, pagesize);
        QueryWrapper<CourseVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("c.gmt_create");
        String subjectId = courseQueryVO.getSubjectId();
        String subjectParentId = courseQueryVO.getSubjectParentId();
        String teacherId = courseQueryVO.getTeacherId();
        String title = courseQueryVO.getTitle();
        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.eq("c.subject_id", subjectId);
        }
        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.eq("c.subject_parent_id", subjectParentId);
        }
        if (!StringUtils.isEmpty(teacherId)) {
            queryWrapper.eq("c.teacher_id", teacherId);
        }
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("c.title", title);
        }
        List<CourseVO> records = eduCourseMapper.selectConditonCourse(pageParm, queryWrapper);
        return pageParm.setRecords(records);
    }

    @Override
    public boolean deleteCourseCoverByCourseId(String id) {
        EduCourse course = eduCourseMapper.selectById(id);
        if (course != null) {
            String cover = course.getCover();
            if (cover != null) {
                ResultVO resultVO = serviceOssFeignClient.removeTeacherAvatarByUrl(cover);
                return resultVO.isIsok();
            }
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean removeCourseById(String id) {
        //先删除course对应下的video
        QueryWrapper<EduVideo> eduVideoQueryWrapper = new QueryWrapper<>();
        eduVideoQueryWrapper.eq("course_id", id);
        int delete = eduVideoMapper.delete(eduVideoQueryWrapper);//如果delete为0的话，证明这个course在高并发下被别人删除了

        QueryWrapper<EduChapter> eduChapterQueryWrapper = new QueryWrapper<>();
        eduChapterQueryWrapper.eq("course_id", id);
        int delete1 = eduChapterMapper.delete(eduChapterQueryWrapper);

        QueryWrapper<EduCourseCollect> eduCourseCollectQueryWrapper = new QueryWrapper<>();
        eduCourseCollectQueryWrapper.eq("course_id", id);
        int delete2 = eduCourseCollectMapper.delete(eduCourseCollectQueryWrapper);

        QueryWrapper<EduComment> eduCommentQueryWrapper = new QueryWrapper<>();
        eduCommentQueryWrapper.eq("course_id", id);
        int delete3 = eduCommentMapper.delete(eduCommentQueryWrapper);

        int delete4 = eduCourseDescriptionMapper.deleteById(id);

        boolean b = this.removeById(id);//这个service层本类的一个方法
        return b;
    }

    @Override
    public CoursePublishVO queryCoursePublishById(String id) {
        CoursePublishVO coursePublishVO = eduCourseMapper.selectCoursePublishVOById(id);
        return coursePublishVO;
    }

    @Override
    public boolean updateCourseStatusById(String id) {
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(id);
        eduCourse.setStatus(eduCourse.COURSE_NORMAL);
        boolean b = this.updateById(eduCourse);
        return b;
    }

    @Override
    public List<EduCourse> getSiteCourseByCondition(SiteCourseQueryVO siteCourseQueryVO) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(siteCourseQueryVO.getSubjectParentId())) {
            wrapper.eq("subject_parent_id", siteCourseQueryVO.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(siteCourseQueryVO.getSubjectId())) {
            wrapper.eq("subject_id", siteCourseQueryVO.getSubjectId());
        }
        if (!StringUtils.isEmpty(siteCourseQueryVO.getBuyCountSort())) {
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(siteCourseQueryVO.getPriceSort())) {
            wrapper.orderByDesc("price");
        }
        if (!StringUtils.isEmpty(siteCourseQueryVO.getGmtCreateSort())) {
            wrapper.orderByDesc("gmt_create");
        }
        List<EduCourse> courseList = eduCourseMapper.selectList(wrapper);
        return courseList;
    }

    @Override
    public SiteCourseVO querySiteCourseVOById(String id) {

        SiteCourseVO siteCourseVO = eduCourseMapper.selectSiteCourseVOById(id);
        Long viewCount = siteCourseVO.getViewCount();
        siteCourseVO.setViewCount(viewCount+1);
        //下面就要改数据库,该course的浏览量了
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(siteCourseVO.getId());
        eduCourse.setViewCount(viewCount+1);
        eduCourseMapper.updateById(eduCourse);
        return siteCourseVO;
    }

    @Override
    @Cacheable(value = "index",key = "'queryCourseForSiteIndex'")
    public List<EduCourse> queryCourseForSiteIndex() {
        Page<EduCourse> page = new Page<>(1, 8);
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        eduCourseMapper.selectPage(page, wrapper);
        List<EduCourse> courses = page.getRecords();
        return courses;
    }

    @Override
    public CourseDto queryCourseDtoById(String id) {
        CourseDto courseDto = eduCourseMapper.selectCourseDtoById(id);
        return  courseDto;
    }
}
